import {computed, onMounted, reactive, ref} from 'vue'
import to from 'await-to-js'
import {getAccountInfoSync, getSystemInfo} from '@/utils/uni-api-wrap/sys'
import {isInvalidData} from '@/utils/utils'

export const useSys = () => {

  const safeArea = reactive({
    bottom: 0,
    left: 0,
    right: 0,
    top: 0
  })
  const screenHeight = ref(0)
  const version = ref('')
  const tabberOccupyHeight = computed(() => (safeArea.bottom * 2) + 88) // 页面自定义tabber栏占高
  const devicePlatform = ref('')


  const getSafeArea = async () => {
    const [err, result] = await to(getSystemInfo())
    if (isInvalidData(err)) {
      Object.assign(safeArea, result.safeAreaInsets)
      devicePlatform.value = result.platform
      screenHeight.value = result.screenHeight
    }
  }

  const getVersion = async () => {
    const { miniProgram } = getAccountInfoSync()
    version.value = miniProgram?.version
  }

  onMounted( () => {
    getSafeArea()
    getVersion()
  })

  return { safeArea, screenHeight, version, devicePlatform, tabberOccupyHeight }
}
